package com.longrise.co.ui.mine.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.co.R;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carfiles.widget.AddPhotoDialog;
import com.longrise.co.ui.mine.contract.MineContract;
import com.longrise.co.ui.mine.model.MineModel;
import com.longrise.co.ui.mine.model.RxModifyBackData;
import com.longrise.co.ui.mine.model.UserInfo;
import com.longrise.co.ui.mine.presenter.MinePresenter;
import com.longrise.co.utils.Constants;
import com.longrise.co.utils.StringUtils;
import com.ly.common.base.BaseFragment;
import com.ly.common.commonutils.ImageLoaderUtils;

import java.io.File;

import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by luoyang on 2017-7-20.
 */

public class MyProfileFragment extends BaseFragment<MinePresenter, MineModel> implements MineContract.MineView<UserInfo>,AddPhotoDialog.OnSelectPhotoListener, InvokeListener, TakePhoto.TakeResultListener {

    @Bind(R.id.head_title)
    TextView headTitle;
    @Bind(R.id.photo)
    ImageView photo;
    @Bind(R.id.nick_name)
    TextView nickName;
    @Bind(R.id.mobile)
    TextView mobile;
    @Bind(R.id.is_real_name)
    TextView isRealName;
    @Bind(R.id.real_name)
    TextView realName;
    @Bind(R.id.card_num)
    TextView cardNum;
    @Bind(R.id.is_real_name_iv)
    ImageView mRealNameIv;
    @Bind(R.id.is_real_name_alone)
    TextView mRealNameAlone;
    @Bind(R.id.mine_photo)
    RelativeLayout mMinePhoto;
    private UserInfo mUserInfo;

    public static final int RX_MODIFY_NICK = 1;
    public static final int RX_MODIFY_MOBILE = 2;
    public static final int RX_P_FEED_BACK = 3;
    public static final int RX_REAL_NAME = 5;

    private boolean isAuth = true;
    private AddPhotoDialog mAddPhotoDialog;
    private TakePhoto takePhoto;
    private Uri imageUri;
    private InvokeParam invokeParam;
    private TImage mCurrentImage;
    private OnSuccessListener onSuccessListener;
    private boolean isChangeToPhoto =false;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_mine_data;
    }
    public void setOnSuccessListener(OnSuccessListener onSuccessListener1) {
        onSuccessListener = onSuccessListener1;
        Log.e("onSuccessListener",onSuccessListener+"1");
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        setText(headTitle, "我的资料");
        initPhotoSelect();
        mUserInfo = (UserInfo) getArguments().getSerializable("userInfo");
        initData();
        Log.e("onSuccessListener",onSuccessListener+"");
        mRxManager.on(Constants.RX_EVENT_MODIFY_NICK, new Action1<RxModifyBackData>() {
            @Override
            public void call(RxModifyBackData s) {
                switch (s.type) {
                    case RX_MODIFY_NICK:
                        nickName.setText(s.value);
                        break;
                    case RX_MODIFY_MOBILE:
                        mobile.setText(s.value);
                        break;
                    case RX_REAL_NAME:
                        isAuth = false;
                        mUserInfo.setCardno(s.cardNo);
                        mUserInfo.setName(s.name);
                        setText(mRealNameAlone, "已认证");
                        setAuthInfo();
                        break;
                }

            }
        });
    }

    private void initData() {
        if (mUserInfo == null) {
            return;
        }
        if (!StringUtils.isEmpty(mUserInfo.getPhoto())) {
            ImageLoaderUtils.displayCircle(getContext(), photo, mUserInfo.getPhoto());
        }
        setText(nickName, mUserInfo.getNickname());
        setText(mobile, mUserInfo.getMobile());
        setText(mRealNameAlone, mUserInfo.getAuthstatus());
        isAuth = "未认证".equals(mUserInfo.getAuthstatus());
        setAuthInfo();

    }

    private void setAuthInfo() {
        mRealNameIv.setVisibility(isAuth ? View.VISIBLE : View.GONE);
        isRealName.setVisibility(isAuth ? View.VISIBLE : View.GONE);
        mRealNameAlone.setVisibility(isAuth ? View.GONE : View.VISIBLE);
        if (!isAuth) {
            setText(realName, mUserInfo.getName());
            setText(cardNum, mUserInfo.getCardno());
        }
    }

    public static MyProfileFragment newInstance(UserInfo userInfo) {

        Bundle args = new Bundle();
        args.putSerializable("userInfo", userInfo);
        MyProfileFragment fragment = new MyProfileFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void initAddPhotoDialog() {
        mAddPhotoDialog = new AddPhotoDialog(getContext(), R.style.dialog_style);
        mAddPhotoDialog.setCanceledOnTouchOutside(true);
        mAddPhotoDialog.setOnSelectPhotoListener(this);
//        mAddPhotoDialog.create();
    }

    @OnClick({R.id.head_back, R.id.mine_nick, R.id.mine_mobile, R.id.mine_modify_pwd, R.id.mine_verified, R.id.mine_photo})
    public void onViewClicked(View view) {
        if (checkDoubleClick()) {
            switch (view.getId()) {
                case R.id.mine_photo:
                    //上传照片
                    if (mAddPhotoDialog == null) {
                        initAddPhotoDialog();
                    }
                    mAddPhotoDialog.show();
                    break;
                case R.id.head_back:
                    if(isChangeToPhoto&&onSuccessListener!=null) {
                        onSuccessListener.onSuccess();
                    }
                    _mActivity.onBackPressed();
                    break;
                case R.id.mine_nick:
                     start(ModifyNickNameFragment.newInstance(mUserInfo.getNickname()));
                    break;
                case R.id.mine_mobile:
//                    start(ModifyMobileFragment.newInstance(mUserInfo.getMobile()));
                    break;
                case R.id.mine_modify_pwd:
                    start(ModifyPwdFragment.newInstance());
                    break;
                case R.id.mine_verified:
                    //实名认证
                    /*if (mUserInfo != null && "0".equals(mUserInfo.getAuthstatus())) {
                        start(VerifiedFragment.newInstance());
                    }*/
                    if (isAuth) {
                        start(VerifiedFragment.newInstance());
                    }
                    break;
            }
        }
    }

    private void initPhotoSelect() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        configTakePhotoOption();
    }

    private void configTakePhotoOption() {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    @Override
    public void takeSuccess(TResult result) {
        try {
            if (result != null && result.getImage() != null) {
                mCurrentImage = result.getImage();
                String imageInfo = com.longrise.co.utils.StringUtils.File2Base64(result.getImage().getOriginalPath());
                EntityBean bean = new EntityBean();
                bean.set("userflag", CommonPara.getInstance().getUserFlag());
                bean.set("userimg", imageInfo);
                bean.set("user", CommonPara.getInstance().getUser());
                bean.set("sign", CommonPara.getInstance().getEnUserFlag());
                mPresenter.modifyUserInfo(bean);
//              ImageLoaderUtils.display(getContext(), drivingLicense, mCurrentImage.getOriginalPath());
//              mPresenter.uploadPhoto(imageInfo, "5");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void takeFail(TResult result, String msg) {
        showErrorTip(msg);
    }

    @Override
    public void takeCancel() {

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    @Override
    public void onSelect(int type) {
        switch (type) {
            case AddPhotoDialog.SELECT_ALBUM:
                //选择相册
                takePhoto.onPickFromGallery();
//                        onPickMultiple(MAX_UPLOAD_IMAGE + 1 - mAdapter.getData().size());
                break;
            case AddPhotoDialog.SELECT_PHOTO:
                //拍照
                takePhoto.onPickFromCapture(imageUri);
                break;
            case AddPhotoDialog.SELECT_CANCEL:
                break;
        }
        mAddPhotoDialog.dismiss();
    }

    @Override
    public void requestSuccess(UserInfo userInfo) {
        if(userInfo == null) {
            return ;
        }
        if(photo != null && !StringUtils.isEmpty(userInfo.getPhoto())) {
            ImageLoaderUtils.displayCircle(getContext(), photo, userInfo.getPhoto());
        }else{
            photo.setImageResource(R.drawable.test_photo);
        }
    }

    @Override
    public void onRequestComplete() {
        isChangeToPhoto= true;
        if(photo != null) {
            ImageLoaderUtils.displayCircle(getContext(), photo,  mCurrentImage.getOriginalPath());
        }else{
            photo.setImageResource(R.drawable.test_photo);
        }

    }

    @Override
    public void modifySuccess() {
        showLongToast("修改头像成功");
    }
    public interface OnSuccessListener{
        void onSuccess();
    }
}
